<?php

namespace Blog\Controller;

use Think\Hook;

class ArticleController extends BaseController
{
    protected $config = array(
        'login_auth' => false,
        'ctrl_auth' => false
    );

    public function index()
    {
        $st = D('Article')->where(['status' => 1])->field('date_format(post_date,"%Y-%m-%d") st_date')->group('post_date')->order('st_date desc')->select();
        dump($st);
        $this->display();
    }

    public function view($id)
    {
        $model = D('Article');
        $row = $model->where(['status' => 1, 'id' => $id])->find();
        if (!$row)
            $this->error('文章不存在');
        if (!session('post_view_' . $id) && $this->_me['id'] != $row['author']) {
            // 浏览量 递增
            session('post_view_' . $id, 1);
            $model->where(['id' => $id])->setInc('view');
        }
        $this->_web('title', $row['title']);
        $breadcrumb = [];
        if ($row['category_name']) {
            $breadcrumb[] = ['title' => $row['category_name'], 'url' => U('index', ['cid' => $row['category_id']])];
        }
        $breadcrumb[] = ['title' => $row['title'], 'url' => U('', ['id' => $id]),];
        $this->_web('breadcrumb', $breadcrumb);
        $replies = D('ArticleReply')->order('create_time desc')->get_post_reply($id, 10);
        $p = array(
            'replies' => &$replies,
            'article' => &$row,
        );
        Hook::listen('blog_article_view', $p);
        $this->assign('replies', $replies['data']);
        $this->assign('reply_page', $replies['html']);
        $this->assign('blog_reply_info', cookie('blog_reply_info'));
        $this->assign('row', $row);
        $this->display();
    }

    public function reply($post_id)
    {
        $has = D('Article')->where(['status' => 1, 'id' => $post_id])->count();
        if (!$has)
            $this->error('文章不存在');
        $model = D('ArticleReply');
        $time_limit = 10;
        Hook::listen('blog_reply_begin', $p = ['post_id' => $post_id, 'time_limit' => &$time_limit]);
        $data = $model->create();
        if (!$data) {
            $this->error($model->getError());
        } else if ($time_limit && (time() - cookie('blog_reply_info')['create_time']) <= $time_limit) {
            $this->error('回复太频繁了, 请' . $time_limit . '秒后再回复');
        }
        if ($this->_me) $data['uid'] = $this->_me['id'];

        $res = $model->add($data);
        cookie('blog_reply_info', $data, ['expire' => 86400 * 30]);
        if ($res) {
            Hook::listen('blog_reply_success', $post_id);
            $this->success('回复成功', U('view', ['id' => $post_id]));
        }
    }
}